use std::fs::{File, OpenOptions};
use rand::{Rng, rngs::OsRng};
use serde_json::{json, Value,to_string_pretty};
use uuid::Uuid;
use std::io::{Read, Write};
use cursor_reset::storage;

fn main() {
    //根据操作系统获取用户的文件地址
    let path = storage::get_storage_file();
    if !path.exists() {
        panic!("file not exist: {}", path.display());
    }
    //备份数据
    if let Err(err) = storage::backup_file(&path) {
        panic!("Backup failed: {}", err);
    }
    //读取旧数据
    let mut file = File::open(&path)
        .expect("Failed to open file");
    let mut contents = String::new();
    file.read_to_string(&mut contents).expect("Failed to read file");
    //json
    let mut data:Value  = serde_json::from_str(&contents).expect("Failed to parse JSON");

    //生成序列号
    let machine_id = OsRng.gen::<[u8; 32]>();
    let mac_machine_id = OsRng.gen::<[u8; 32]>();
    let dev_device_id = Uuid::new_v4();
    data["telemetry.machineId"] = json!(hex::encode(machine_id));
    data["telemetry.macMachineId"] = json!(hex::encode(mac_machine_id));
    data["telemetry.devDeviceId"] = json!(dev_device_id.to_string());

    // 将修改后的数据写回文件
    let mut file = OpenOptions::new().write(true).truncate(true).open(&path)
        .expect("Failed to open file for writing");
    let data_str = serde_json::to_string_pretty(&data).expect("Failed to convert JSON to string");
    file.write_all(data_str.as_bytes()).expect("Failed to write data to file");

    //打印结果
    println!("🎉 Device IDs have been successfully reset. The new device IDs are: ");
    let device_ids = json!({
        "machineId": hex::encode(machine_id),
        "macMachineId": hex::encode(mac_machine_id),
        "devDeviceId": dev_device_id.to_string(),
    });
    let formatted_json = to_string_pretty(&device_ids).expect("Failed to format JSON");
    println!("{}", formatted_json);
}
